package com.mls.fivedistrict.controller.backend;


import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mls.fivedistrict.common.PageFilter;
import com.mls.fivedistrict.common.RequestHolder;
import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.controller.BaseController;
import com.mls.fivedistrict.exception.CustomerException;
import com.mls.fivedistrict.pojo.ManagerUser;
import com.mls.fivedistrict.server.ManagerUserService;
import com.mls.fivedistrict.util.JsonUtils;
import com.mls.fivedistrict.util.Md5Utils;
import com.mls.fivedistrict.util.jedis.RedisPoolUtil;
import com.mls.fivedistrict.util.validator.BeanValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Five Team
 * @since 2018-07-02
 */
@RestController("backendManagerUserController")
@RequestMapping("/api/manager")
public class ManagerUserController extends BaseController {
    @Autowired
    ManagerUserService managerUserService;
    @Value("#{settings['token.expirationTime']}")
    private Integer tokenExpirationTime;

    @PostMapping(path = "/v1/login")
    public ServiceResponse login(@RequestBody Map<String, String> parama) {
        String username = Optional.ofNullable(parama.get("username")).orElseThrow(() -> new CustomerException("用户名不存在"));
        String password = Optional.ofNullable(parama.get("password")).orElseThrow(() -> new CustomerException("密码不存在"));
        String captcha = Optional.ofNullable(parama.get("captcha")).orElseThrow(() -> new CustomerException("验证码不存在"));
        String sCaptcha = null;
        String managerPassword = Md5Utils.encryptPassword(password, "manager");
        Wrapper wrapper = Condition.create();
        wrapper.eq("phone", username);
        wrapper.eq("password", managerPassword);
        ManagerUser managerUser = managerUserService.selectOne(wrapper);
        if (managerUser != null) {
            sCaptcha = RedisPoolUtil.get(managerUser.getPhone());
            if (sCaptcha == null || !sCaptcha.equals(captcha)) {
                return ServiceResponse.createErrorResponse("验证码错误");
            }
            RedisPoolUtil.del(managerUser.getPhone());
            managerUser.setPassword("");
            String userInfo = JsonUtils.objectToJson(managerUser);
            String token = UUID.randomUUID().toString();
            RedisPoolUtil.setEx(token, userInfo, 4 * 60 * 60);
            managerUser.setToken(token);
            return ServiceResponse.createSuccessResponse(managerUser);
        }

        return ServiceResponse.createErrorResponse("用户名或密码不存在");
    }

    /**
     * 添加
     *
     * @param managerUser
     * @return
     */
    @PostMapping("/v1/managerUser")
    public ServiceResponse addManagerUser(@RequestBody ManagerUser managerUser) {
        BeanValidator.check(managerUser);
        String managerPassword = Md5Utils.encryptPassword(managerUser.getPassword(), "manager");
        managerUser.setPassword(managerPassword);
        boolean insert = managerUserService.insert(managerUser);
        if (insert) {
            return ServiceResponse.createSuccessResponse("添加管理员成功");
        }
        return ServiceResponse.createErrorResponse("添加管理员失败");
    }

    /**
     * 删除
     *
     * @param managerUserId
     * @return
     */
    @DeleteMapping("/v1/managerUser/{managerUserId}")
    public ServiceResponse deleteManagerUser(@PathVariable Long managerUserId) {
        Optional.ofNullable(managerUserId).orElseThrow(() -> new CustomerException("管理员用户id不能为空"));
        ManagerUser managerUser = new ManagerUser();
        managerUser.setId(managerUserId);
        managerUser.setDelete(true);
        boolean update = managerUserService.updateById(managerUser);
        if (update) {
            return ServiceResponse.createSuccessResponse("删除成功");
        } else {
            return ServiceResponse.createErrorResponse("删除失败");
        }
    }

    /**
     * 修改
     *
     * @param managerUserId
     * @param managerUser
     * @return
     */
    @PutMapping("/v1/managerUser/{managerUserId}")
    public ServiceResponse updateManagerUser(@PathVariable Long managerUserId, @RequestBody ManagerUser managerUser) {
        Optional.ofNullable(managerUserId).orElseThrow(() -> new CustomerException("管理员用户id不能为空"));
        Optional.ofNullable(managerUser).orElseThrow(() -> new CustomerException("管理员不能为空"));
        managerUser.setId(managerUserId);
        boolean update = managerUserService.updateById(managerUser);
        if (update) {
            return ServiceResponse.createSuccessResponse("修改管理员成功");
        }
        return ServiceResponse.createErrorResponse("修改管理员失败");
    }

    /**
     * 重置密码接口
     * @param managerUserId
     * @param managerUser
     * @return
     */
    @PutMapping("/v1/resetPassword/{managerUserId}")
    public ServiceResponse resetPassword(@PathVariable Long  managerUserId,@RequestBody ManagerUser managerUser){
        Optional.ofNullable(managerUserId).orElseThrow(() -> new CustomerException("管理员用户id不能为空"));
        String managerPassword = Md5Utils.encryptPassword(managerUser.getPassword(), "manager");
        managerUser.setPassword(managerPassword);
        managerUser.setId(managerUserId);
        boolean update = managerUserService.updateById(managerUser);
        if (update) {
            return ServiceResponse.createSuccessResponse("重置成功");
        }
        return ServiceResponse.createErrorResponse("重置失败");

    }
    /**
     * 查询单个管理员
     *
     * @param managerUserId
     * @return
     */
    @GetMapping("/v1/managerUser/{managerUserId}")
    public ServiceResponse getManagerUser(@PathVariable Long managerUserId) {
        Optional.ofNullable(managerUserId).orElseThrow(() -> new CustomerException("管理员用户id不能为空"));
        ManagerUser managerUser = managerUserService.selectById(managerUserId);
        if (null != managerUser) {
            return ServiceResponse.createSuccessResponse(managerUser);
        }
        return ServiceResponse.createErrorResponse("查无该管理员");
    }

    /**
     * 管理员列表
     *
     * @return
     */
    @GetMapping("/v1/managerUsers")
    public ServiceResponse getManagerUserList() {
        PageFilter pageFilter = RequestHolder.getPageFilter();
        PageHelper.startPage(pageFilter.getPageNum(), pageFilter.getPageSize());
        List selectList = managerUserService.selectList(pageFilter.getWrapper());
        PageInfo pageInfo = new PageInfo<ManagerUser>(selectList, 5);
        return ServiceResponse.createSuccessResponse(pageInfo);
    }
}

